package org.df.ulab.bot.plugins.cmd;

import org.df.ulab.bot.api.message.Message;
import org.df.ulab.bot.util.communication.BaseCommunicationService;
import org.df.ulab.bot.util.message.BaseMessage;
import org.df.ulab.util.io.CmdLineIO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Daniel Filgueiras
 * @since 19/06/2011
 */
public class CommandLineService extends BaseCommunicationService {
	
	private static final Logger logger = LoggerFactory.getLogger(CommandLineService.class) ;
	
	@Override
	public void run() {
		CmdLineIO io = new CmdLineIO();
		io.setTimeout(1000 * 10);
		
		try {
			while(keepAlive) {
				Message toSend = getNextMessage();
				while (toSend != null) {
					System.out.println(toSend.toText());
					toSend = getNextMessage();
				}
				
				String text = io.readString();
				if (text != null && text.length() > 0) {
					addIncome(BaseMessage.getBaseMessage(text));
				}
			}
		} catch(Exception e) {
			logger.error("Error on running COM service",e);
		}
		logger.info("Service was shutdown");
	}
	
	@Override
	public void reply(Message oriMessage, CharSequence message) {
		post(BaseMessage.getBaseMessage(message));
	}
	
	@Override
	public void reply(Message message, DefaultMsgs msg) {
		reply(message, msg.toString());
	}

	@Override
	public boolean subscribe(String remoteId) {
		return false;
	}
	
	@Override
	public boolean unsubscribe(String remoteId) {
		return false;
	}
}

